package com.wytec.xywzxw.utils;

import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import java.util.Properties;

@Component
public class EmailUtils {
    @Value("${email.user}")
    private String user;
    @Value("${email.pass}")
    private String pass;
    @Value("${email.port}")
    private int port;
    @Value("${email.host}")
    private String host;
    @Value("${email.auth}")
    private String auth;
    @Value("${email.tls}")
    private String tls;
    @Value("${email.debug}")
    private boolean debug;

    private static EmailUtils emailUtils;

    @PostConstruct
    public void init() {
        emailUtils = this;
    }

    public static Session createSession() {
        //	账号信息
        String username = emailUtils.user;//	邮箱发送账号
        String password = emailUtils.pass;//	邮箱授权码

        //	创建一个配置文件，并保存
        Properties props = new Properties();

        props.put("mail.smtp.host", emailUtils.host);//	SMTP主机名
        props.put("mail.smtp.port", emailUtils.port);//	主机端口号
        props.put("mail.smtp.auth", emailUtils.auth);//	是否需要用户认证
        props.put("mail.smtp.starttls.enable", emailUtils.tls);//启用TlS加密

        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // TODO Auto-generated method stub
                return new PasswordAuthentication(username, password);
            }
        });

        //  控制台打印调试信息
        session.setDebug(emailUtils.debug);
        return session;
    }
}
